package com.lf.connect;

import com.csvreader.CsvReader;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class CSV implements FileControl {

    private CsvReader csvreader = null;
    private static final Logger LOGGER = Logger.getLogger(CSV.class);

    public CSV() {

    }

    public boolean setFile(String csvfile) {
        boolean ok = false;
        try {
            csvreader = new CsvReader(csvfile, ',', Charset.forName("GBK"));
            ok = true;
        } catch (Exception e) {
            LOGGER.error("文件操作错误：" + e.getMessage());
        }
        return ok;
    }

    public boolean isReady() {
        return csvreader != null;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public List getRows(Object obj) {
        List rowobj = new ArrayList();
        if (!isReady())
            return rowobj;
        try {
            csvreader.readRecord();
            // csvreader.readHeaders();
            String[] headers = csvreader.getValues();// getHeaders();
            int i;
            DataMap dm = new DataMap();
            while (csvreader.readRecord()) {
                Object newobj = null;
                try {
                    newobj = obj.getClass().newInstance();
                } catch (Exception e) {
                    LOGGER.error("重新实例化对象时出错：" + e.getMessage());
                }
                for (i = 1; i < headers.length; i++) {
                    dm.Mapping(headers[i].toLowerCase(), csvreader.get(i),
                            newobj);
                }
                rowobj.add(newobj);
            }
        } catch (IOException e) {
            LOGGER.error("文件读取出错：" + e.getMessage());
        }
        return rowobj;
    }

    public void close() {
        if (csvreader != null) {
            csvreader.close();
            csvreader = null;
        }
    }
}
